import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import { LogLevelsScale } from 'bs-logger/dist/logger/level'
import { createLogger } from 'bs-logger'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60 * 1000,// request timeout
  // retry: 3, //设置全局重试请求次数（最多重试几次请求）
  // retryDelay: 1000, //设置全局请求间隔
})

// request interceptor
service.interceptors.request.use(
  config => {

    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['Content-Type'] = 'application/x-www-form-urlencoded' multipart/form-data
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = `Bearer ${getToken()}`
    }
    // config.headers['Content-Type'] = 'multipart/form-data'
    // console.log("config", config)
    return config
  },
  error => {
    // do something with request error

    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    const fileType = ["application/pdf", "application/msword", "application/zip", "application/x-rar-compressed", "application/vnd.ms-excel", "image/jpeg", "image/png"]

    if (res.code != 200) {

      if (fileType.indexOf(response.headers["content-type"]) != -1) {
        //获取文件名
        let fileName = response.headers["content-disposition"].split(";")[1].split("=")[1]
        // 去掉引号
        fileName = fileName.replace(/\"/g, "")

        return {
          fileName: fileName,
          res: res,
          type: response.headers["content-type"]
        }

      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return res
      }

    } else {

      return res
    }
  },
  error => {

    // if (error.message.indexOf('timeout') != -1) {
    //   return Message.error('网络超时');
    // } else if (error.message == 'Network Error') {
    //   return Message.error('网络连接错误');
    // }


    switch (error.response.status) {
      case 400:
        Message({
          message: "请求错误(400)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 401:
        Message({
          message: "未授权，请重新登录(401)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 403:
        Message({
          message: "拒绝访问(403)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 404:
        Message({
          message: "请求出错(404)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 500:
        Message({
          message: "服务器错误(500)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 501:
        Message({
          message: "服务未实现(501)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 502:
        Message({
          message: "网络错误(502)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      case 503:
        Message({
          message: "服务不可用(503)",
          type: 'error',
          duration: 5 * 1000,
        })
        break
      default:
        Message({
          message: `连接出错(${error.response.status})!`,
          type: 'error',
          duration: 5 * 1000,
        })

    }


    return Promise.reject(error)
  }
)

export default service
